package m.jclecai.com.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import m.jclecai.com.R;
import m.jclecai.com.activity.LotteryPayActivity;
import m.jclecai.com.activity.WebHelperActivity;
import m.jclecai.com.adapter.BettingRXJAdapter;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.Content;
import m.jclecai.com.bean.MatchInfoBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.contents.LotteryType;
import m.jclecai.com.inter.IAdapterChange;
import m.jclecai.com.inter.OnResultCallback;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.OkHttpClientManager;
import m.jclecai.com.utils.ToastUtil;
import m.jclecai.com.utils.ViewHolderUtil;
import m.jclecai.com.utils.http.FastOk;

public class BetRXJ_SFCActivity extends BaseActivity implements IAdapterChange, View.OnClickListener, RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.include_multiple_context)
    EditText include_multiple_context;
    private TextView tv_term;
    private TextView tv_date;
    private ListView lv_rjc;
    private BettingRXJAdapter adapter;
    private PopupWindow pop;
    private List<Content> itemList;
    private TextView tv_number;

    private int mode; //彩种 (任选九，胜负彩)
    private int selectLength; //可选择比赛场数
    private int allMoney;//金额
    private RadioGroup rg_tab;
    private String type;
    MatchInfoBean bean;
    String vote = "1",code;

    @Override
    protected int getContentView() {
        return R.layout.betting_rjc_activity;
    }

    private void initSelectBox() {
        View view = getLayoutInflater().inflate(R.layout.rxj_select_box, null);
        rg_tab = (RadioGroup) view.findViewById(R.id.rg_tab);
        rg_tab.setOnCheckedChangeListener(this);
    }

    @Override
    protected void initView() {
        leftOptionText("");
        rightOptionText("发起合买");
        Button bt_bottom_left = (Button) findViewById(R.id.bt_bottom_left);
        bt_bottom_left.setOnClickListener(this);
        Button bt_bottom_right = (Button) findViewById(R.id.bt_bottom_right);
        bt_bottom_right.setOnClickListener(this);

        tv_number = (TextView) findViewById(R.id.tv_number);
        tv_term = (TextView) findViewById(R.id.tv_term);
        tv_date = (TextView) findViewById(R.id.tv_date);
        lv_rjc = (ListView) findViewById(R.id.lv_rjc);
        adapter = new BettingRXJAdapter(this);
        lv_rjc.setAdapter(adapter);

    }

    private void initPopupView() {
        View pv = View.inflate(this, R.layout.lottery_help_popupview, null);
        pop = new PopupWindow(pv, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        TextView tv_trendChart = (TextView) pv.findViewById(R.id.tv_trendChart);
        pv.findViewById(R.id.tv_play_desc).setOnClickListener(this);
        tv_trendChart.setVisibility(View.GONE);
        TextView tv_lotteryHistory = (TextView) pv.findViewById(R.id.tv_kaijiang);
        tv_lotteryHistory.setOnClickListener(this);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
    }

    @Override
    protected void initData() {
        itemList = new LinkedList<>();
        initSelectBox();
        initPopupView();
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        if (type.equals("rxj") || type.equals("rjc")) {
            type = "rjc";
            mode = 0;
            switchMode();
        } else if (type.equals("sfc")) {
            mode = 1;
            switchMode();
        }
        setNumber();
        getMatchInfo(type);
    }

    //合买
    @OnClick(R.id.tv_right_option)
    void jointPurchase() {
        //getCodes();
        /**
         * 此处提交之前先判断用户是否登录
         */
        //得到倍数和code和金额

        new AlertDialog.Builder(this)
                .setMessage("功能开发中...")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();

/*        Log.e(TAG, "totalNum=" + Integer.valueOf(vote));
        Log.e(TAG, "multiple=" +  Integer.valueOf(include_multiple_context.getText().toString()));
        Log.e(TAG, "totalMoney=" + allMoney);
        Log.e(TAG, "num=" + 1);
        Log.e(TAG, "type=" + type);
        Log.e(TAG, "codes=" + code);
        if (itemList.size() < selectLength) {
            DisPlay("至少选择" + selectLength + "场比赛");
            return;
        }

        Intent intent = new Intent(this, JointPurchaseActivity.class);
        intent.putExtra("totalNum", Integer.valueOf(vote));
        intent.putExtra("multiple",  Integer.valueOf(include_multiple_context.getText().toString()));
        intent.putExtra("totalMoney", allMoney*Integer.valueOf(include_multiple_context.getText().toString()));
        intent.putExtra("num", 1);
        intent.putExtra("type", type);
        intent.putExtra("codes", code+";");
        startActivity(intent);*/

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_bottom_left:
                clearInfo();
                break;
            case R.id.bt_bottom_right:
//                Log.e("data", JSON.toJSONString(itemList));
//                startActivityForResult(new Intent(this, BettingSfc_RjcActivity.class).
//                        putExtra("bean", JSON.toJSONString(itemList)).
//                        putExtra("perfix", type).
//                        putExtra("selectLength",selectLength),
//                        Constant_Result.SYNCHRONIZATION);
                showBuyInfo();
                break;
            //走势图
            case R.id.tv_trendChart:
                break;
            //历史开奖
            case R.id.tv_kaijiang:
                Intent intent = new Intent(this, LotteryHistoryActivity.class);
                intent.putExtra("type", type);
                startActivity(intent);
                this.finish();
                break;
            case R.id.tv_play_desc:
                Intent helpIntent = new Intent(this, WebHelperActivity.class);
                helpIntent.putExtra("title", "玩法介绍");
                helpIntent.putExtra("code", type);
                helpIntent.putExtra("isLocal", true);
                startActivity(helpIntent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant_Result.SYNCHRONIZATION) {
            //清空了
            clearInfo();
            if (data != null) {
                //同步数据
                String str = data.getStringExtra("bean");
                List<Content> mData = JSON.parseArray(str, Content.class);
                itemList.clear();
                itemList.addAll(mData);
                List<Content> lists = adapter.getList();
                for (int i = 0; i < lists.size(); i++) {
                    for (int j = 0; j < mData.size(); j++) {
                        if (lists.get(i).getBout_index().equals(mData.get(j).getBout_index())) {
                            lists.remove(i);
                            lists.add(i, mData.get(j));
                        }
                    }
                }
                adapter.notifyDataSetChanged();
                setNumber();
            }
        }
    }

    //清除信息
    private void clearInfo() {
        itemList.clear();
        for (int i = 0; i < adapter.getCount(); i++) {
            Content item = (Content) adapter.getItem(i);
            item.setOdd_away_select(false);
            item.setOdd_draw_select(false);
            item.setOdd_home_select(false);
            item.setOdd_select_number(0);
        }
        adapter.notifyDataSetChanged();
        setNumber();
    }

    private void getMatchInfo(String type) {
        showDialog();
        OkHttpClientManager.Param Url = new OkHttpClientManager.Param("url", Constant_Url.MATCH_INFO);
        OkHttpClientManager.Param Type = new OkHttpClientManager.Param("type", type);
        OkHttpClientManager.Param[] param = new OkHttpClientManager.Param[]{Url, Type};
        try {
            OkHttpClientManager.getInstance().asynPost(new OnResultCallback() {
                @Override
                public void onGetResult(String json) {

                    String[] strings = FastOk.get(json, String[].class);
                    if(strings == null) return;
                    String string = strings[0];
                    Log.i("解析后", string);
                    bean = FastOk.get(string, MatchInfoBean.class);
                    setViewInfo(bean);
                    dissDialog();
                }

                @Override
                public void onError() {
                    dissDialog();
                    ToastUtil.showToast(BetRXJ_SFCActivity.this, R.string.connect_failure);
                }
            }, param);
        } catch (IOException e) {
            e.printStackTrace();
            dissDialog();
        }
    }

    private void setViewInfo(MatchInfoBean bean) {
        if(bean == null) return;
        tv_term.setText(bean.getTermNo() + "期");
        tv_date.setText(bean.getStop_sale_time() + "截止");
        for (int i = 0; i < bean.getContent().size(); i++) {
            adapter.addData(bean.getContent().get(i));
        }
    }

    @Override
    public View onItemChanged(final int position, View convertView, ViewGroup parent) {

        final Content item = (Content) adapter.getItem(position);
        convertView = LayoutInflater.from(this).inflate(R.layout.betting_rjc_item, parent, false);

        TextView tv_gameName = ViewHolderUtil.get(convertView, R.id.tv_gameName);
        TextView tv_homeName = ViewHolderUtil.get(convertView, R.id.tv_homeName);
        TextView tv_guestName = ViewHolderUtil.get(convertView, R.id.tv_guestName);
        TextView tv_jjcProjectOne = ViewHolderUtil.get(convertView, R.id.tv_jjcProjectOne);
        TextView tv_jjcProjectTwo = ViewHolderUtil.get(convertView, R.id.tv_jjcProjectTwo);
        TextView tv_jjcProjectThree = ViewHolderUtil.get(convertView, R.id.tv_jjcProjectThree);

        String[] split = item.getMatch_time().split(" ");
        String substring = split[0].substring(5, split[0].length());

        tv_gameName.setText(item.getMatch_name() + "\n" + substring + "\n" + split[1]);
        tv_homeName.setText(item.getHome_team());
        tv_guestName.setText(item.getAway_team());
        tv_jjcProjectOne.setText(item.getOdd_home());
        tv_jjcProjectOne.setTag("0_" + type + "_0_" + item.getOdd_home() + "_胜_3");
        tv_jjcProjectTwo.setText(item.getOdd_draw());
        tv_jjcProjectTwo.setTag("0_" + type + "_1_" + item.getOdd_draw() + "_平_1");
        tv_jjcProjectThree.setText(item.getOdd_away());
        tv_jjcProjectThree.setTag("0_" + type + "_2_" + item.getOdd_away() + "_负_0");

        if (item.isOdd_home_select()) {
            tv_jjcProjectOne.setBackgroundResource(R.color.baseRed);
            tv_jjcProjectOne.setTextColor(Color.WHITE);
        } else {
            tv_jjcProjectOne.setBackgroundResource(R.color.white);
            tv_jjcProjectOne.setTextColor(Color.BLACK);
        }

        if (item.isOdd_draw_select()) {
            tv_jjcProjectTwo.setBackgroundResource(R.color.baseRed);
            tv_jjcProjectTwo.setTextColor(Color.WHITE);
        } else {
            tv_jjcProjectTwo.setBackgroundResource(R.color.white);
            tv_jjcProjectTwo.setTextColor(Color.BLACK);
        }

        if (item.isOdd_away_select()) {
            tv_jjcProjectThree.setBackgroundResource(R.color.baseRed);
            tv_jjcProjectThree.setTextColor(Color.WHITE);
        } else {
            tv_jjcProjectThree.setBackgroundResource(R.color.white);
            tv_jjcProjectThree.setTextColor(Color.BLACK);
        }

        tv_jjcProjectOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.isOdd_home_select()) {
                    item.setOdd_select_number(item.getOdd_select_number() - 1);
                    item.setOdd_home_select(false);
                } else {
                    item.setOdd_select_number(item.getOdd_select_number() + 1);
                    item.setOdd_home_select(true);
                }
                itemStateChange(position, item);
                checkData(v, item);
            }
        });

        tv_jjcProjectTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.isOdd_draw_select()) {
                    item.setOdd_select_number(item.getOdd_select_number() - 1);
                    item.setOdd_draw_select(false);
                } else {
                    item.setOdd_select_number(item.getOdd_select_number() + 1);
                    item.setOdd_draw_select(true);
                }
                itemStateChange(position, item);
                checkData(v, item);
            }
        });

        tv_jjcProjectThree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.isOdd_away_select()) {
                    item.setOdd_select_number(item.getOdd_select_number() - 1);
                    item.setOdd_away_select(false);
                } else {
                    item.setOdd_select_number(item.getOdd_select_number() + 1);
                    item.setOdd_away_select(true);
                }
                itemStateChange(position, item);
                checkData(v, item);
            }
        });

        noSale(tv_jjcProjectOne,item.getOdd_home());
        noSale(tv_jjcProjectTwo,item.getOdd_draw());
        noSale(tv_jjcProjectThree,item.getOdd_away());
        return convertView;
    }

    void noSale(TextView view,String txt){
//        view.setTextColor(ContextCompat.getColorStateList(this, R.color.black_white_selector));
        view.setEnabled(true);
        if(TextUtils.isEmpty(txt) || "0".equals(txt)){
            view.setText("未开售");
            view.setEnabled(false);
            view.setTextColor(ContextCompat.getColor(this, R.color.b));
        }
    }
    void checkData(View v, Content mItem) {
        //记录点击的数据
        Map<String, Map<String, String>> cMap;
        if (mItem.getMap() == null) {
            cMap = new HashMap<>();
            mItem.setMap(cMap);
        } else {
            cMap = mItem.getMap();
        }
        String tag = v.getTag().toString();
        String key = tag.substring(0, 1);
        String value = tag;
        if (cMap.get(key) != null) {
            //有则删除 无则添加 - 等同于没选中则选中 选中了则取消
            if (cMap.get(key).get(value) != null) {
                cMap.get(key).remove(value);
            } else {
                cMap.get(key).put(value, value);
            }
        } else {
            Map<String, String> map = new HashMap<>();
            map.put(value, value);
            cMap.put(key, map);
        }
    }

    /**
     * @category 判断item的添加状态
     */
    private void itemStateChange(int position, Content item) {
        if (item.isOdd_home_select() || item.isOdd_draw_select() || item.isOdd_away_select()) {
            if (!itemList.contains(item)) {
                if (itemList.size() >= selectLength) {
                    DisPlay("最多选择"+selectLength+"场");
                    item.setOdd_away_select(false);
                    item.setOdd_home_select(false);
                    item.setOdd_draw_select(false);
                    item.setOdd_select_number(item.getOdd_select_number() - 1);
                    adapter.notifyDataSetChanged();
                    return;
                }
                if (position < itemList.size())
                    itemList.add(position, item);
                else
                    itemList.add(item);
            }
        } else {
            if (itemList.contains(item)) {
                itemList.remove(item);
            }
        }
        adapter.notifyDataSetChanged();
        setNumber();
    }

    /**
     * @category 设置注数信息
     */
    private void setNumber() {
        getCodes();
        if (itemList.size() >= selectLength) {
            tv_number.setText(Html.fromHtml(String.format(getString(R.string.rjc_bonus_optimiiza)
                    ,allMoney,vote,include_multiple_context.getText().toString())));
        } else if (itemList.size() == 0) {
            tv_number.setText("请选择比赛");
        } else {
            int number = selectLength - itemList.size();
            tv_number.setText("已选" + itemList.size() + "场,还差" + number + "场");
        }
    }

    int num = 1;
    //过关倍数
    @OnTextChanged(R.id.include_multiple_context)
    void multiple(Editable s) {
        if (TextUtils.isEmpty(include_multiple_context.getText().toString())) {
            return;
        }
        if (s.toString().equals("0")){
            include_multiple_context.setText("1");
        }
        num = Integer.parseInt(s.toString());
        if (itemList.size() >= selectLength){
            getCodes();
            tv_number.setText(Html.fromHtml(String.format(getString(R.string.rjc_bonus_optimiiza)
                    ,allMoney,vote,s.toString())));
        }

    }

    private void showBuyInfo() {
        if (itemList.size() < selectLength) {
            DisPlay("至少选择" + selectLength + "场比赛");
            return;
        }
        /**
         * 此处提交之前先判断用户是否登录
         */
        Intent intent = new Intent(this, LotteryPayActivity.class);
        intent.putExtra(PAY_MULTIPLE, String.valueOf(include_multiple_context.getText().toString()));
        //得到倍数和code和金额
        intent.putExtra(PAY_CODES, code);
        intent.putExtra(PAY_MONEY, String.valueOf(allMoney));
        intent.putExtra(PAY_VOTENUMS, vote);
        intent.putExtra(PAY_TYPE, type);
        intent.putExtra(PAY_NAME, "自购");
        if (bean != null)
            intent.putExtra(PAY_TERM, BaseUtils.strNoNull(bean.getTermNo()));
        startActivityForResult(intent, Constant_Result.CLOSEPAGE);
    }

    //获取code
    String getCodes() {
        StringBuilder sb = new StringBuilder();
        ArrayList<Content> mDatas = adapter.getList();
        int mult = 1;
        for (int i = 0; i < mDatas.size(); i++) {
            Content content = mDatas.get(i);
            if (content.getOdd_select_number() > 0)
                mult = mult * content.getOdd_select_number();
            if (content.isOdd_home_select())
                sb.append("3");
            if (content.isOdd_draw_select())
                sb.append("1");
            if (content.isOdd_away_select())
                sb.append("0");
            if (!content.isOdd_home_select() && !content.isOdd_draw_select() && !content.isOdd_away_select())
                sb.append("#");
            if (i < mDatas.size() - 1)
                sb.append(",");
        }
        allMoney = mult*2*num;
        vote = "" + mult;
        sb.append(":"+ LotteryType.DEFAULT);
        return code = sb.toString();
    }

    private void switchMode() {
        switch (mode) {
            case 0:
                ((RadioButton) rg_tab.getChildAt(0)).setChecked(true);
                setTitle("任选九");
                mode = 0;
                selectLength = 9;

                break;
            case 1:
                ((RadioButton) rg_tab.getChildAt(1)).setChecked(true);
                setTitle("胜负彩");
                mode = 0;
                selectLength = 14;
                break;
        }
    }

    @Override
    protected void close() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        if (itemList.size() > 0)
            showAlertDialog("提示", "返回大厅将清空所有数据?", "取消", "确认", null,
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            clearInfo();
                            finish();
                        }
                    });
        else {
            clearInfo();
            finish();
        }
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        clearInfo();
        switch (checkedId) {
            case R.id.rb_rxj:
                mode = 0;
                switchMode();
                break;
            case R.id.rb_sfc:
                mode = 1;
                switchMode();
                break;
        }
    }
}
